package cn.ubeta.b2c.common;

import android.app.Activity;
import android.os.Bundle;

import cn.ubeta.b2c.DemoData;
import cn.ubeta.b2c.R;
import cn.ubeta.b2c.bean.ProductInfo;
import cn.ubeta.b2c.cart.CheckoutActivity;
import cn.ubeta.b2c.utils.ToastHelper;

import java.util.HashSet;

/**
 * Created by denny on 16/8/22.
 */

public class CartCommon {

    private static int sCartCount = 0;
    private static HashSet<ICartListener> mList = new HashSet<>();

    public interface ICartListener {
        void notifyShopCartCountChanged(int count, boolean showAnimation);
    }

    public static void addListener(ICartListener listener) {
        if (mList.contains(listener)) return;
        mList.add(listener);
    }

    public static void removeListener(ICartListener listener) {
        if (mList.contains(listener)) {
            mList.remove(listener);//有风险吗？
        }
    }

    private static void notifyChanged(int count, boolean showAnimation) {
        for (ICartListener l : mList) {
            if (l != null) {
                l.notifyShopCartCountChanged(count, showAnimation);
            }
        }
    }

    public static void setCartCount(int count) {
        sCartCount = count;
        notifyChanged(sCartCount, false);
    }

    public static int getCartCount() {
        return sCartCount;
    }

    /**
     * 添加购物车
     * @param skuId
     */
    public static void add2Cart(long skuId) {
        // TODO 待删除,测试代码
        //AppConfig.putCartCount(sCartCount);
        DemoData.getCartInfo().addCart(new ProductInfo(skuId));
        DemoData.putCartInfo(DemoData.getCartInfo());

        sCartCount = DemoData.getCartInfo().getCount();

        notifyChanged(sCartCount, false);
        ToastHelper.show("添加购物车成功");
    }

    /**
     * 立即购买
     */
    public static void checkout(Activity activity, ProductInfo info) {
        Bundle data = new Bundle();
        data.putParcelable(CheckoutActivity.PARAM_PRODUCT_INFO, info);
        if (LoginCommon.isLogin()) {
            CheckoutActivity.gotoActivity(activity, CheckoutActivity.class, data);
            activity.overridePendingTransition(R.anim.in_right_to_left, android.R.anim.fade_out);
        } else {
            AnalyseActivity.gotoActivityWithLogin(activity, CheckoutActivity.class, data);
        }
    }
}
